import wave
import numpy as np
from scipy import signal
from matplotlib import pyplot as plt

# 我们需要生成一个100~400Hz的扫频波

# 生成的时长
WAVE_DURATION = 300
WAVE_SEGMENT_DURATION = 0.1
WAVE_SEGMENTS = int(WAVE_DURATION // WAVE_SEGMENT_DURATION)
# 采样率
WAVE_SAMPLE_RATE = 48000
# 音频音量
WAVE_VOLUMN = 29000
# 低频
WAVE_LOWER_FREQ = 100
WAVE_HIGHER_FREQ = 400

t = np.arange(0,WAVE_SEGMENT_DURATION,1.0/WAVE_SAMPLE_RATE)

rising_wave_data = np.array(signal.chirp(t,WAVE_LOWER_FREQ,WAVE_SEGMENT_DURATION,WAVE_HIGHER_FREQ,method='linear')) * WAVE_VOLUMN
falling_wave_data = np.array(signal.chirp(t,WAVE_HIGHER_FREQ,WAVE_SEGMENT_DURATION,WAVE_LOWER_FREQ,method='linear')) * WAVE_VOLUMN
rising_wave_data = rising_wave_data.astype(np.short)
falling_wave_data = falling_wave_data.astype(np.short)

plt.plot(t,rising_wave_data)
plt.show()

wave_file = wave.open('chirp.wav','wb')
wave_file.setnchannels(1)
wave_file.setsampwidth(2)
wave_file.setframerate(WAVE_SAMPLE_RATE)
for i in range(WAVE_SEGMENTS):
    if i%2 == 0:
        wave_file.writeframes(rising_wave_data.tobytes())
    else:
        wave_file.writeframes(falling_wave_data.tobytes())
wave_file.close()